package com.smart.buss.ctrl;

import com.smart.buss.service.*;
import com.smart.buss.vo.*;
import com.smart.primary.common.common.BaseCtrl;
import com.smart.primary.common.common.Constants;
import com.smart.primary.common.util.AjaxResult;
import com.smart.primary.common.util.DateUtil;
import com.smart.primary.common.util.PropertiesUtil;
import com.smart.primary.common.util.Util;
import com.smart.primary.sys.vo.User;
import com.smart.primary.util.MoneyUtil;
import com.smart.primary.util.UploadUtil;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/buss/task/log")
public class BussTaskLogController extends BaseCtrl {
	private final static Logger logger= Logger.getLogger(BussTaskLogController.class);

	@Autowired
	private BussTaskLogService bussTaskLogService;
	@Autowired
	private BussAccountLogService bussAccountLogService;
	@Autowired
	private BussUserService bussUserService;
	@Autowired
	private BussSetService bussSetService;
	@Autowired
	private BussTaskService bussTaskService;
	@Autowired
	private BussDakaService bussDakaService;
	@Autowired
	private BussDakaLogService bussDakaLogService;

	@RequestMapping
	public AjaxResult getList(BussTaskLog entity) throws Exception{
		List<BussTaskLog> list=bussTaskLogService.queryListByPage(entity);
		String path= PropertiesUtil.getString("res.web.url");
		for(BussTaskLog user:list ){
			if(StringUtils.isNotBlank(user.getImgUpload())){
				String[] arr=user.getImgUpload().split(",");
				String shili="";
				for (String str: arr){
					shili+=path+str+",";
				}
				user.setImgUpload(shili.length()>1?shili.substring(0,shili.length()-1):shili);
			}
		}
		return getResult(entity, list);
	}

	@RequestMapping("/list")
	public List<BussTaskLog> list(BussTaskLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return new ArrayList<>();
		}
		entity.setCheckStatus(1); // 审核成功的
		entity.setField("create_date");
		entity.setOrder("DESC");
		return bussTaskLogService.queryListByPage(entity);
	}
	//http://192.168.0.6:8080/task/buss/task/log/ontask?userId=12345678910
	@RequestMapping("/ontask")
	public AjaxResult ontask(BussTaskLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("未登录");
		}
		BussTaskLog ent=new BussTaskLog();
		ent.setUserId(entity.getUserId());
		ent.setCheckStatus(-1);
		BussTaskLog qbl=bussTaskLogService.queryObject(ent);
		if(qbl==null){
			return AjaxResult.failure("未有在做的任务");
		}
		if(StringUtils.isBlank(qbl.getTaskId())){
			return AjaxResult.failure("任务错误");
		}
		BussTask task=new BussTask();
		task.setId(qbl.getTaskId());
		BussTask qtask=bussTaskService.queryObject(task);
		if(qtask==null){
			return AjaxResult.failure("任务错误");
		}
		String path= PropertiesUtil.getString("res.web.url");
		if(StringUtils.isNotBlank(qtask.getImgIcon())){
			qtask.setImgIcon(path+qtask.getImgIcon());
		}
		if(StringUtils.isNotBlank(qtask.getImgShili())){
			String[] arr=qtask.getImgShili().split(",");
			String shili="";
			for (String str: arr){
				shili+=path+str+",";
			}
			qtask.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
		}
		return AjaxResult.success(qtask);
	}

	/**
	 * 开始任务
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	//http://localhost:8080/task/buss/task/log/start?userId=12345678910&taskId=6b07f71d180f4a25913b040437abd133
	@RequestMapping("/start")
	public AjaxResult start(BussTaskLog entity) throws Exception{

		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		logger.info("开始任务缓存中的手机号。。"+entity.getUserId());
		if(StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("未登录");
		}
		if(StringUtils.isBlank(entity.getTaskId())){
			return AjaxResult.failure("参数错误");
		}
		BussTask task=new BussTask();
		task.setId(entity.getTaskId());
		task.setTaskStatus(1);
		BussTask taskq=bussTaskService.queryObject(task);
		if(taskq==null){
			return AjaxResult.failure("该任务已下架");
		}
		/**
		 * 判断该任务是否在审核
		 */
		BussTaskLog ent=new BussTaskLog();
		ent.setUserId(entity.getUserId());
		ent.setTaskId(entity.getTaskId());
		ent.setCheckStatus(0);
		BussTaskLog qbl=bussTaskLogService.queryObject(ent);
		if(qbl!=null ) {// 存在任务审核中的任务
			return AjaxResult.failure("任务<"+taskq.getName()+">已审核中");
		}

		/**
		 * 判断任务是否有存在的任务
		 */
		ent.setTaskId(null);
		ent.setCheckStatus(-1);
		qbl=bussTaskLogService.queryObject(ent);
		if(qbl!=null ){// 存在任务
			Boolean bool=System.currentTimeMillis()/1000>(qbl.getUpdateDate().getTime()/1000+taskq.getTimeOut());
			if(bool){ // 任务超时 更新任务
				qbl.setTaskId(entity.getTaskId());
				qbl.setUpdateDate(new Date());
				bussTaskLogService.update(qbl);
			}else {
				return AjaxResult.failure("有任务尚未完成");
			}
		}else {
			ent.setId(Util.getUUID());
			ent.setTaskId(entity.getTaskId());
			bussTaskLogService.insert(ent);
		}
		return AjaxResult.success(null,"成功抢到<"+taskq.getName()+">的任务");
	}

	@RequestMapping("/save")
	public AjaxResult save(BussTaskLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}

		if(StringUtils.isBlank(entity.getTaskId()) ||  StringUtils.isBlank(entity.getUserId()) ){ // 图片判断取消 || StringUtils.isBlank(entity.getImgUpload())
			return AjaxResult.failure("参数错误");
		}
		if(StringUtils.isBlank(entity.getName()) || StringUtils.isBlank(entity.getPhone())){
			return AjaxResult.failure("缺少个人信息");
		}
		BussTaskLog ent=new BussTaskLog();
		ent.setTaskId(entity.getTaskId());
		ent.setUserId(entity.getUserId());
		ent.setCheckStatus(-1);
		BussTaskLog qbl=bussTaskLogService.queryObject(ent);
		
		BussTask task=new BussTask();
		task.setId(entity.getTaskId());
		task=bussTaskService.queryObject(task);
		
		if(qbl==null ){
			return AjaxResult.failure("<"+task.getName()+">任务尚未完成，请先完成或放弃");
		}
		task=new BussTask();
		task.setId(entity.getTaskId());
		task.setTaskStatus(1);
		BussTask query=bussTaskService.queryObject(task);
		if(query==null){
			return AjaxResult.failure("任务不存在");
		}

		BussUser user=new BussUser();
		user.setId(entity.getUserId());
		BussUser queryus=bussUserService.queryObject(user);
		if(queryus==null){
			return AjaxResult.failure("用户不存在");
		}

		//任务累加使用数量
		query.setStartNum(query.getStartNum()+1);
		bussTaskService.update(query);
/*		//手机号姓名更新
		if(!(entity.getName().equals(queryus.getName()) && entity.getPhone().equals(queryus.getPhone()))){
			queryus.setName(entity.getName());
			queryus.setPhone(entity.getPhone());
			bussUserService.update(queryus);
		}*/
		//更新记录
		qbl.setUserPrice(query.getUserPrice());
		qbl.setImgUpload(entity.getImgUpload());
		qbl.setName(entity.getName());
		qbl.setPhone(entity.getPhone());
		qbl.setCheckStatus(0);
		bussTaskLogService.update(qbl);
		return AjaxResult.saveSuccess();

	}

	/**
	 *  放弃任务
	 */
	@RequestMapping("/del")
	public AjaxResult del(BussTaskLog entity) throws Exception{

		logger.info("开始删除任务======================");

		String phone = getUserMobile();
		logger.info("/task/getOne中获取到的主键："+phone);
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}
		if(StringUtils.isBlank(entity.getTaskId()) || StringUtils.isBlank(entity.getUserId())){
			return AjaxResult.failure("参数错误");
		}
		try {
			entity.setCheckStatus(-1);
			BussTaskLog qlog=bussTaskLogService.queryObject(entity);
			if(qlog!=null ){
				bussTaskLogService.delete(qlog.getId());
				return AjaxResult.success(null,"任务已放弃");
			}
		}catch (Exception e){
			return AjaxResult.failure("删除失败");
		}
		return AjaxResult.failure("删除失败");
	}


	/**
	 *获取任务
	 */
	@RequestMapping("/gettask")
	public AjaxResult gettask() throws Exception{

		String phone = getUserMobile();
		Boolean bool=bussUserService.getDakeVip(phone);
		if(!bool){
			return AjaxResult.failure("暂无任务");
		}

		BussTask entity=new BussTask();
		entity.setIshide(1);
		BussTask task=bussTaskService.queryObject(entity);
		if(task==null){
			return AjaxResult.failure("暂无任务");
		}

		task.setTaskStatus(0);
		String path= PropertiesUtil.getString("res.web.url");
		if(StringUtils.isNotBlank(task.getImgIcon())){
			task.setImgIcon(path+task.getImgIcon());
		}

		if(StringUtils.isNotBlank(task.getImgShili())){
			String[] arr=task.getImgShili().split(",");
			String shili="";
			for (String str: arr){
				shili+=path+str+",";
			}
			task.setImgShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
		}
		if(StringUtils.isNotBlank(task.getImgUploadShili())){
			String[] arr=task.getImgUploadShili().split(",");
			String shili="";
			for (String str: arr){
				shili+=path+str+",";
			}
			task.setImgUploadShili(shili.length()>1?shili.substring(0,shili.length()-1):shili);
		}
		return AjaxResult.success(task);
	}

	@RequestMapping("/sub")
	public AjaxResult sub(BussTaskLog entity) throws Exception{
		String phone = getUserMobile();
		if(StringUtils.isNotBlank(phone)){
			entity.setUserId(phone);
		}

		if(StringUtils.isBlank(entity.getTaskId()) ||  StringUtils.isBlank(entity.getUserId()) ){ // 图片判断取消 || StringUtils.isBlank(entity.getImgUpload())
			return AjaxResult.failure("参数错误");
		}
		if(StringUtils.isBlank(entity.getName()) || StringUtils.isBlank(entity.getPhone())){
			return AjaxResult.failure("缺少个人信息");
		}

		BussTask task=new BussTask();
		task.setId(entity.getTaskId());
		task.setTaskStatus(1);
		BussTask query=bussTaskService.queryObject(task);
		if(query==null){
			return AjaxResult.failure("任务不存在");
		}

		BussUser user=new BussUser();
		user.setId(entity.getUserId());
		BussUser queryus=bussUserService.queryObject(user);
		if(queryus==null){
			return AjaxResult.failure("用户不存在");
		}
		//任务累加使用数量
		query.setStartNum(query.getStartNum()+1);
		bussTaskService.update(query);

		entity.setUserPrice(0.0);
		entity.setCheckStatus(0);
		entity.setType(1);
		entity.setId(Util.getUUID());
		bussTaskLogService.insert(entity);

		/**
		 * 设置打卡记录
		 */
		BussDaka bdaka=new BussDaka();
		bdaka.setStatus(0);
		BussDaka querydaka=bussDakaService.queryObject(bdaka);
		if(querydaka!=null && StringUtils.isNotBlank(querydaka.getIssueNumber())){
			BussDakaLog log=new BussDakaLog();
			log.setDakaId(querydaka.getIssueNumber());
			log.setDakaStatus(0);
			log.setUserId(phone);
			log.setType(1);
			log.setId(Util.getUUID());
			bussDakaLogService.insert(log);
		}
		return AjaxResult.saveSuccess();

	}

	@RequestMapping("/out")
	public AjaxResult out(String id,String date) throws Exception{
		if(stringToDate(date)!=null){
			BussTaskLog entity=new BussTaskLog();
			entity.setTaskId(id);
			entity.setCheckStatus(0);
			entity.setCreateDate(stringToDate(date));
			List<BussTaskLog> list=bussTaskLogService.queryList(entity);
			for (BussTaskLog log: list) {
				log.setCheckStatus(2);
				bussTaskLogService.update(log);
			}
		}
		return AjaxResult.updateSuccess();
	}

	/**
	 * 导入
	 */
	@RequestMapping("/daoru")
	@Transactional
	public AjaxResult upload(MultipartFile file,String taskId){

		String fileName= UploadUtil.upLoad(file,request,"/upload/xsl/",true,true);
		try {
			Workbook wb=Workbook.getWorkbook(new File(fileName));
			Sheet ss=wb.getSheet(0);
			Map<Integer,String> m=new HashMap<Integer,String>();
			int rows = ss.getRows();
			for(int i=1;i<rows;i++){
				String phone = ss.getCell(0,i).getContents();
				// 是空白的话直接跳过
				if(StringUtils.isBlank(phone)){
					continue;
				}
				// 根据手机号查找记录
				BussTaskLog bt=new BussTaskLog();
				bt.setPhone(phone);
				bt.setCheckStatus(1);
				bt.setTaskId(taskId);
				BussTaskLog log1= bussTaskLogService.queryObject(bt);

				bt.setCheckStatus(0);
				List<BussTaskLog> list= bussTaskLogService.queryList(bt);
				if(log1!=null){ // 已有审核过的任务 直接跳出
					if(list !=null){
						for (BussTaskLog log: list) {
							if(log!=null ){ //  存在未审核的任务  //   不再判断是否有上传图片  StringUtils.isNotBlank(log.getImgUpload())
								log.setCheckStatus(1);
								// 重复任务
								check1(log);
							}
						}
					}
				}else {
					if(list !=null && list.size()>0){
						for(int a=0;a<list.size();a++ ){
							if(a==0){
								list.get(a).setCheckStatus(1);
								// 资金变动
								check(list.get(a));
							}else {
								list.get(a).setCheckStatus(1);
								// 重复任务
								check1(list.get(a));
							}
						}
					}
				}
				m.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.updateSuccess();
	}


	/**
	 *  资金变动
	 * @param entity
	 * @throws Exception
	 */
	private synchronized void check (BussTaskLog entity)throws Exception{
		// 审核通过 添加账户记录
		if(entity.getCheckStatus()==1){
			BussAccountLog log=new BussAccountLog();
			log.setId(Util.getUUID());
			log.setUserId(entity.getUserId());
			log.setTaskId(entity.getId());
			log.setPrice(entity.getUserPrice());
			log.setAddSub(1);
			log.setLogtype(1);
			log.setRemarks("自己的订单");
			bussAccountLogService.insert(log);
			// 添加用户 余额
			BussUser user=new BussUser();
			user.setId(entity.getUserId());
			BussUser query=bussUserService.queryObject(user);
			query.setAccount(query.getAccount()+entity.getUserPrice());

			// 存在师傅师傅
			if(StringUtils.isNotBlank(query.getFid())){
				BussUser fu=new BussUser();
				fu.setId(query.getFid());
				BussUser fuser=bussUserService.queryObject(fu);
				if(fuser!=null){
					BussSet set=bussSetService.queryObject(null);
					Double rate=set.getRate();
					Double zuida=set.getZuida();
					if(zuida>query.getFidAccount()){
						BussAccountLog flog=new BussAccountLog();
						flog.setId(Util.getUUID());
						flog.setUserId(query.getFid());
						flog.setTaskId(entity.getId());
						flog.setAddSub(1);
						flog.setLogtype(3);
						flog.setRemarks("徒弟的订单");
						if((entity.getUserPrice()*rate+query.getFidAccount())>zuida){
							flog.setPrice(zuida-query.getFidAccount());
							query.setFidAccount(zuida);
						}else {
							query.setFidAccount(entity.getUserPrice()*rate+query.getFidAccount());
							flog.setPrice(entity.getUserPrice()*rate);
						}
						fuser.setAccount(fuser.getAccount()+flog.getPrice());
						bussAccountLogService.insert(flog);
						bussUserService.update(fuser);
					}
				}
			}
			bussUserService.update(query);
		}
		bussTaskLogService.update(entity);
	}


	/**
	 *  重复任务的处理
	 * @param entity
	 * @throws Exception
	 */
	private synchronized void check1 (BussTaskLog entity)throws Exception{
		// 审核通过 添加账户记录
		if(entity.getCheckStatus()==1){
			BussAccountLog log=new BussAccountLog();
			log.setId(Util.getUUID());
			log.setUserId(entity.getUserId());
			log.setTaskId(entity.getId());
			log.setPrice(0.0);
			log.setAddSub(1);
			log.setLogtype(1);
			log.setRemarks("重复的任务");
			bussAccountLogService.insert(log);
			// 添加用户 余额
		}
		bussTaskLogService.update(entity);
	}

}
